#include "serv_manage.hpp"
#include "meet.hpp"


#include "client/xd_client.hpp"
#include "meet_room.hpp"
#include "conf/conf.hpp"
#include "utils/utils_string.hpp"
#include "wlog.hpp"

namespace bz
{
	
	serv_manage::serv_manage()
		:client_io_(),
		server_io_()
	{
		//edition_ = conf::instance()->get_conf<string>("common/edition");

		//main_ip_=conf::instance()->get_conf<string>(edition_+"/main_ip");
		//main_ip_= conf::instance()->get_conf<string>("common/mcu_ip");

		
		

		

		//smc_client_ = new smc_client(client_io_, "10.0.66.100", "zbtest1", "admin1234.");
	}

	serv_manage::~serv_manage()
	{
	}


	void serv_manage::init(const std::string& mcu_ip)
	{
		main_ip_ = mcu_ip;

		load_all_fme();


		std::thread thd([this] {
			asio::io_context::work work(client_io_);
			client_io_.run();
			});

		thd.detach();

		meet meetModel;
		meetModel.init();
		auto rows = meetModel.index();

		for (auto& it : rows)
		{
			add_meet_room(it.id);

		}



		

		std::thread ths([this] {
			asio::io_context::work work(server_io_);
			server_io_.run();
		});

		

		ths.detach();

		

	}

	void serv_manage::add_meet_room(int& meet_id)
	{
		meet* model = new meet();
		model->id = meet_id;

		auto ret = model->get();

		if (ret)
		{
			model->meet_name = model->name;
			meet_room* room = new meet_room(server_io_,model, main_mcu_);
			meet_room_map_[model->id] = room;
		}
	}

	xd_client* serv_manage::add_mcu(const std::string& ip,const std::string& user, const std::string& pwd)
	{
		auto finder = mcu_map_.find(ip);
		if (finder != mcu_map_.end()) {
			return finder->second;
		}
		
		xd_client*fme = new xd_client(ip, user, pwd);
		mcu_map_[ip] = fme;
		
		return fme;
	}

	meet_room* serv_manage::get_room(int& key)
	{
		auto it = meet_room_map_.find(key);
		if (it != meet_room_map_.end()) {
			return it->second;
		}
		return nullptr;
	}

	async_simple::coro::Lazy<void> serv_manage::del_room(int id)
	{
		meet_room* room = meet_room_map_[id];
		meet_room_map_.erase(id);
		room->before_del();
		co_await async_simple::coro::sleep(20s);
		delete room;

	}

	void serv_manage::load_all_fme()
	{
		//string user = "zbapi1";
		//string pwd = "admin123.";
		string user = conf::instance()->get_conf<string>("common/user");
		string pwd = conf::instance()->get_conf<string>("common/pwd");
		main_mcu_ = new xd_client(main_ip_, user, pwd);
		mcu_map_[main_ip_]= main_mcu_;

		

		
	}


	


	

	void serv_manage::room_device_update()
	{
		for (auto it: meet_room_map_)
		{
			meet_room* room = it.second;
			room->load_device_from_db();
			if (!room->meet_->is_start) 
			{
				room->update_terminal_list();
			}
			
		}
	}
}